﻿using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.WEB.GIMS.Class;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class BidderController : Controller
    {
        public ActionResult Index(int? BidId = null, int? PrId = 0)
        {
            string RecordStatus = "W";
            var service = new BidService.BidServiceClient();
            var service2 = new PurchaseRequestService.PurchaseRequestServiceClient();
            var modelPurchaseRequest = service2.Select(new PurchaseRequest() { PrId = PrId.Value }, new[] { "MasPurchaseMethod" }).FirstOrDefault();

            ViewBag.BidId = BidId;
            ViewBag.PrId = PrId;
            //ViewBag.IsBid = modelPurchaseRequest.MasPurchaseMethod.IsBid ?? false;

            if (BidId != null && BidId > 0)
            {
                var models = service.SelectBidder(new Bidder { BidId = BidId }, new[] { "MasContact" });
                var bidModel = service.SelectBid(new Bid { BidId = BidId.Value }, null).FirstOrDefault();
                RecordStatus = bidModel.RecordStatus;

                ViewBag.bEditable = RecordStatus == Models.SYS.RecordStatus.ApprovedStatus;

                return View(models);
            }
            else if (PrId != null && PrId > 0)
            {
                var models = service.SelectBidder(new Bidder { PrId = PrId }, new[] { "MasContact" });
                RecordStatus = modelPurchaseRequest.RecordStatus;

                ViewBag.bEditable = RecordStatus == Models.SYS.RecordStatus.WaitStatus || RecordStatus == Models.SYS.RecordStatus.ReturnedStatus;

                return View(models);
            }
            else
            {
                throw new Exception("ไม่สามารถแสดงข้อมูลได้ เนื่องจากไม่พบรายการที่ต้องการ");
            }
        }

        public ActionResult Details(int id, bool IsFromOther = false )
        {
            var service = new BidService.BidServiceClient();
            var model = service.SelectBidder(new Models.ICM.Bidder { BidderId = id }, new[] { "Bid", "MasContact", "PurchaseRequest" }).FirstOrDefault();
            ViewBag.IsFromOther = IsFromOther;

            if (model.Bid != null)
            {
                ViewBag.bEditable = model.Bid.RecordStatus == Models.SYS.RecordStatus.WaitStatus || model.Bid.RecordStatus == Models.SYS.RecordStatus.ReturnedStatus;
                ViewBag.bIsBid = true;
            }
            else if (model.PurchaseRequest != null)
            {
                ViewBag.bEditable = model.PurchaseRequest.RecordStatus == Models.SYS.RecordStatus.WaitStatus || model.PurchaseRequest.RecordStatus == Models.SYS.RecordStatus.ReturnedStatus;
                ViewBag.bIsBid = false;
            }

            return View(model);
        }

        public ActionResult Create(int? BidId = null, int? PrId = null)
        {
            var model = new Models.ICM.Bidder();
            model.BidId = BidId;
            model.PrId = PrId;
            model.OfferStatus = "0";
            model.ReceiveStatus = "1";
            model.WinnerStatus = "0";

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Create(Bidder model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new BidService.BidServiceClient();
                    var servicePri = new PurchaseRequestItemService.PurchaseRequestItemServiceClient();
                    var id = service.InsertBidder(model, Class.GimsMembership.CurrentEmpId);

                    var priModels = servicePri.Select(new PurchaseRequestItem() { PrId = model.PrId, RecordStatus = "!" + RecordStatus.DeletedStatus }, null);

                    foreach (PurchaseRequestItem priModel in priModels)
                    {
                        var bidderQuotationModel = new BidderQuotation();

                        bidderQuotationModel.BidderId = id;
                        bidderQuotationModel.Descr = null;
                        bidderQuotationModel.DiscountPercent = 0;
                        bidderQuotationModel.ExcludeVatAmount = 0;
                        bidderQuotationModel.ExtraDiscount = 0;
                        bidderQuotationModel.NetAmount = 0;
                        bidderQuotationModel.Price = 0;
                        bidderQuotationModel.PrItemId = priModel.PrItemId;
                        bidderQuotationModel.Qty = priModel.Qty;
                        bidderQuotationModel.Remarks = null;
                        bidderQuotationModel.Selected = model.BidId == null ? "1" : "0";
                        bidderQuotationModel.SelectedReason = null;
                        bidderQuotationModel.VatAmount = 0;

                        service.InsertBidderQuotation(bidderQuotationModel, Class.GimsMembership.CurrentEmpId);
                    }

                    return RedirectToAction("Details", new { Id = id });
                }

                return View(model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var service = new BidService.BidServiceClient();
            var model = service.SelectBidder(new Models.ICM.Bidder { BidderId = Id }, null).FirstOrDefault();

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int Id, Bidder model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new BidService.BidServiceClient();
                    service.UpdateBidder(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { Id = model.BidderId });
                }

                return View(model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Empty", ex.Message);
                return View(model);
            }
        }

        public ActionResult Delete(int id)
        {
          try
            {
                using (var service = new BidService.BidServiceClient())
                {
                    var PrId = service.SelectBidder(new Models.ICM.Bidder { BidderId = id }, null).FirstOrDefault().PrId;
                    var Collaterals = service.SelectBidderCollateral(new Models.ICM.BidderCollateral { BidderId = id }, null);
                    if (Collaterals != null)
                    {
                        foreach (var Collateral in Collaterals)
                        {
                            service.DeleteBidderCollateral(Collateral.BidderColId, Class.GimsMembership.CurrentEmpId);
                        }
                        //ModelState.AddModelError("Empty", "ไม่สามารถลบข้อมูลได้!กรุณาตรวจสอบข้อมูลคณะกรรมการ");
                        //ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                        //return Json(new { success = false }, JsonRequestBehavior.AllowGet);
                        //return RedirectToAction("Index", new { PrId = PrId });
                    }
                    var Quotations = service.SelectBidderQuotation(new Models.ICM.BidderQuotation { BidderId = id }, null);
                    if (Quotations != null)
                    {
                        foreach (var Quotation in Quotations)
                        {
                            service.DeleteBidderQuotation(Quotation.BidderQuoId, Class.GimsMembership.CurrentEmpId);
                        }
                        //ModelState.AddModelError("Empty", "ไม่สามารถลบข้อมูลได้!กรุณาตรวจสอบข้อมูลคณะกรรมการ");
                        //ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                        //return Json(new { success = false }, JsonRequestBehavior.AllowGet);
                        //return RedirectToAction("Index", new { PrId = PrId });
                    }
                    service.DeleteBidder(id, Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("Index", new { PrId = PrId });
                }
               
            }
            catch (System.ServiceModel.FaultException ex)
            {
                ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    using (var service = new BidService.BidServiceClient())
                    {
                        foreach (int delete in deleteIds)
                        {
                            var BidderId = service.SelectBidderCollateral(new Models.ICM.BidderCollateral { BidderId = delete }, null).FirstOrDefault();
                            if (BidderId != null)
                            {
                                //ModelState.AddModelError("Empty", "ไม่สามารถลบข้อมูลได้!กรุณาตรวจสอบข้อมูลคณะกรรมการ");
                                ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                                return Json(new { success = false });
                            }
                            var BidderId2 = service.SelectBidderQuotation(new Models.ICM.BidderQuotation { BidderId = delete }, null).FirstOrDefault();
                            if (BidderId2 != null)
                            {
                                //ModelState.AddModelError("Empty", "ไม่สามารถลบข้อมูลได้!กรุณาตรวจสอบข้อมูลคณะกรรมการ");
                                ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                                return Json(new { success = false });

                            }
                            service.DeleteBidder(delete, Class.GimsMembership.CurrentEmpId);
                        }
                    }
                }

                ModelState.AddModelError("Empty", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");
                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Empty", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        public ActionResult ToGateway(int id)
        {
            try
            {
                string strResult = "";
                var announceService = new AnnounceService.AnnounceServiceClient();
                var PrItemService = new PurchaseRequestItemService.PurchaseRequestItemServiceClient();
                var BidService = new BidService.BidServiceClient();
                var systemControlService = new SysSystemControlService.SysSystemControlServiceClient();
                var PrItemList = PrItemService.Select(new PurchaseRequestItem { PrId = id }, new[] { "PurchaseRequest", "MasResourceItem.MasUnit", "MasBudgetExpense" }).ToList();
                var BidderList = BidService.SelectBidder(new Bidder() { PrId = id }, new[] { "MasContact" }).ToList();
                var SystemControl = systemControlService.Select();

                if (BidderList != null && BidderList.Count > 0)
                {
                    foreach (var BidderInfo in BidderList)
                    {
                        string strTaxCode = BidderInfo.MasContact.TaxCode.Trim().Replace(" ", "").Replace("-", "");

                        if (!string.IsNullOrWhiteSpace(strTaxCode))
                        {
                            strResult = announceService.CreateAnnounceService(PrItemList.ToArray(), SystemControl.SystemName, "", "", "", "", "", strTaxCode, "");
                        }
                        else
                        {

                        }

                        if (strResult == "")
                        {

                        }
                    }
                }
                else
                {
                    strResult = announceService.CreateAnnounceService(PrItemList.ToArray(), SystemControl.SystemName, "", "", "", "", "", "", "");
                }

                if (strResult == "")
                {
                    strResult = "บันทึกเรียบร้อย";
                }

                return Json(new { success = true, message = strResult });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        //public void SendData(int? BidderId, List<PurchaseRequestItem> PrItemList)
        //{
            
        //}
    }
}
